package main

import (
	"fmt"
	"net"
	"os"
)

func HandleError1(info string, err error) {
	if err != nil {
		fmt.Println(info, " err", err)
		os.Exit(2)
	}
}
func main() {
	listener, err := net.Listen("tcp", "127.0.0.1:8008")
	HandleError1("listen", err)
	defer listener.Close()

	//阻塞监听
	conn, err := listener.Accept()
	HandleError1("accpet", err)
	defer conn.Close()

	//获取文件名
	buf := make([]byte, 4096)
	n, err := conn.Read(buf)
	HandleError1("read", err)

	fileName := string(buf[:n])

	//回写ok给发送端
	conn.Write([]byte("ok"))

	//获取文件内容
	recvFile(conn, fileName)
}

func recvFile(conn net.Conn, fileName string) {
	//创建文件
	f, err := os.Create(fileName)
	HandleError1("creat", err)
	defer f.Close()

	//从网络中读数据，写入本地文件
	buf := make([]byte, 4096)
	for {
		n, _ := conn.Read(buf)
		if n == 0 {
			fmt.Println("接收完毕")
			return
		}
		//写入本地文件
		f.Write(buf[:n])
	}
}
